#include "dirmanage.h"
#include "ui_dirmanage.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QFile>
#include <QFileDialog>
#include <QDomDocument> //文件
#include <QDomProcessingInstruction> //格式头部
#include <QDomElement>  //元素
#include <QTextStream> //文件流
#include <QPrinter>
#include <QTextDocument>
#include <QTextBlock>
#include <QDesktopServices>
#include <QUrl>
#define cout qDebug() << "[" << __FILE__ << ":" << __LINE__ << "]"

DirManage::DirManage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DirManage)
{
    ui->setupUi(this);

    initForm(); //锁定编辑

    initTableWidget(); //初始化tableWidget

    ui->stackedWidget->setCurrentIndex(0);

    showCadreFileData();

    //锁定编辑
    connect(ui->buttonLock,SIGNAL(clicked()),this,SLOT(lockEdit()));
    //打印
    //connect(ui->buttonPrint,SIGNAL(clicked()),this,SLOT(sendPrintSlot()));

}

DirManage::~DirManage()
{
    delete ui;
}

//初始化锁定
void DirManage::initForm()
{
    ui->lineEdit->setEnabled(false);
    ui->buttonFind->setEnabled(false);
    ui->buttonEdit->setEnabled(false);
    ui->buttonPrint->setEnabled(false);
    ui->buttonInOut->setEnabled(false);
    ui->buttonAdd->setEnabled(false);
    ui->buttonDel->setEnabled(false);
    ui->buttonUp->setEnabled(false);
    ui->buttonDown->setEnabled(false);
    ui->buttonInsert->setEnabled(false);
}

//使能按钮
void DirManage::enableForm()
{
    ui->lineEdit->setEnabled(true);
    ui->buttonFind->setEnabled(true);
    ui->buttonEdit->setEnabled(true);
    ui->buttonPrint->setEnabled(true);
    ui->buttonInOut->setEnabled(true);
    ui->buttonAdd->setEnabled(true);
    ui->buttonDel->setEnabled(true);
    ui->buttonUp->setEnabled(true);
    ui->buttonDown->setEnabled(true);
    ui->buttonInsert->setEnabled(true);
}

//初始化tableWidget
void DirManage::initTableWidget()
{
    ui->tableWidget_da->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_da->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    ui->tableWidget_da->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
    ui->tableWidget_da->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头的背景色
    ui->tableWidget_da->setStyleSheet("selection-background-color:rgb(173,216,230);"); //设置选中行的背景色

    initTableWidget_ml(ui->tableWidget_ml_1);
    initTableWidget_ml(ui->tableWidget_ml_2);
    initTableWidget_ml(ui->tableWidget_ml_3);
    initTableWidget_ml(ui->tableWidget_ml_4);
    initTableWidget_ml(ui->tableWidget_ml_5);
    initTableWidget_ml(ui->tableWidget_ml_6);
    initTableWidget_ml(ui->tableWidget_ml_7);
    initTableWidget_ml(ui->tableWidget_ml_8);
    initTableWidget_ml(ui->tableWidget_ml_9);
    initTableWidget_ml(ui->tableWidget_ml_10);
    initTableWidget_ml(ui->tableWidget_ml_11);
    initTableWidget_ml(ui->tableWidget_ml_12);
    initTableWidget_ml(ui->tableWidget_ml_13);
    initTableWidget_ml(ui->tableWidget_ml_14);
    initTableWidget_ml(ui->tableWidget_ml_15);
    initTableWidget_ml(ui->tableWidget_ml_16);
}

//初始化档案目录tableWidget_ml_X
void DirManage::initTableWidget_ml(QTableWidget * tableWidget_ml)
{
    tableWidget_ml->verticalHeader()->setVisible(false); //不显示左边序号
    tableWidget_ml->horizontalHeader()->setFixedHeight(30); //表头高
    tableWidget_ml->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    tableWidget_ml->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
    tableWidget_ml->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}"); //设置表头的背景色
    tableWidget_ml->setStyleSheet("selection-background-color:rgb(173,216,230);"); //设置选中行的背景色
}

//锁定编辑
void DirManage::lockEdit()
{
    QString str = ui->buttonLock->text();
    //qDebug()<< str;

    if(str == "编辑(F1)")
    {
        //qDebug()<<"OK";
        ui->buttonLock->setText("锁定(F1)");
        enableForm();
    }
    else
    {
        ui->buttonLock->setText("编辑(F1)");
        initForm();
    }
}

//查询显示干部档案信息
void DirManage::showCadreFileData()
{
    QSqlQuery query;
    //query.exec("select CadreName,UnitID,Birth,NativePlace,FileNum,FileSite,RollNum,CopyNum,Remark,CadreInfo.IDNum from CadreInfo,File where CadreInfo.IDNum = File.IDNum");
    query.exec("select CadreName,IDNum,UnitID,Birth,NativePlace,Sex from CadreInfo");
    while(query.next()) //一行一行遍历
    {
        int rowc = ui->tableWidget_da->rowCount();//获取行数
        ui->tableWidget_da->insertRow(rowc);
        //干部名称/证件号码
        ui->tableWidget_da->setItem(rowc,0,new QTableWidgetItem(query.value(0).toString()));
        if(query.value(5).toString()== "1")
            ui->tableWidget_da->setItem(rowc,1,new QTableWidgetItem("男"));
        if(query.value(5).toString()== "2")
            ui->tableWidget_da->setItem(rowc,1,new QTableWidgetItem("女"));
        ui->tableWidget_da->setItem(rowc,2,new QTableWidgetItem(query.value(1).toString()));
        //单位
        QString sqlUnit = QString("select unitname from unit where unitid = '%1'").arg(query.value(2).toString());
        QSqlQuery queryUnit;
        queryUnit.exec(sqlUnit);
        while(queryUnit.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,5,new QTableWidgetItem(queryUnit.value(0).toString()));
        }
        //ui->tableWidget_da->setItem(rowc,4,new QTableWidgetItem(query.value(2).toString()));
        //转入转出时间
        QString sqlInTime = QString("select FileRecTime from FileReceive where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryInTime;
        queryInTime.exec(sqlInTime);
        while(queryInTime.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,3,new QTableWidgetItem(queryInTime.value(0).toString()));
        }
        QString sqlOutTime = QString("select FileOutTime from FileOut where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryOutTime;
        queryOutTime.exec(sqlOutTime);
        while(queryOutTime.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,4,new QTableWidgetItem(queryOutTime.value(0).toString()));
        }
        //现任职务
        QString sqlPost = QString("select PostName from Post where QualifyType = '0' and IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryPost;
        queryPost.exec(sqlPost);
        while(queryPost.next()) //一行一行遍历
        {
            ui->tableWidget_da->setItem(rowc,6,new QTableWidgetItem(queryPost.value(0).toString()));
        }
        //出生时间/籍贯等
        for(int i = 7; i<9;i++)
        {
            ui->tableWidget_da->setItem(rowc,i,new QTableWidgetItem(query.value(i-4).toString()));
        }
        //档案信息
        QString sqlFile = QString("select FileNum,FileSite,RollNum,CopyNum,Remark from File where IDNum = '%1'").arg(query.value(1).toString());
        QSqlQuery queryFile;
        queryFile.exec(sqlFile);
        while(queryFile.next()) //一行一行遍历
        {
            for(int i = 9; i<14;i++)
            {
                ui->tableWidget_da->setItem(rowc,i,new QTableWidgetItem(queryFile.value(i-9).toString()));
            }
        }
    }

    int rows = ui->tableWidget_da->rowCount();
    QString newtext = QString(" 共: %1 条").arg(rows);
    ui->label_2->setText(newtext);
}

//上方内部干部查找
void DirManage::on_buttonFind_clicked()
{
    int newrows = 0;
    int rows = ui->tableWidget_da->rowCount();
    QString gbName = ui->lineEdit->text();
    qDebug()<< gbName;
    if ("" == gbName)
    {//判断输入是否为空
        for (int i = 0; i < rows; i++)
        {
            newrows = rows;
            ui->tableWidget_da->setRowHidden(i, false);//显示所有行
        }
    }
    else
    {
        QList <QTableWidgetItem *> item = ui->tableWidget_da->findItems(gbName, Qt::MatchContains);

        for (int i = 0; i < rows; i++)
        {
            ui->tableWidget_da->setRowHidden(i, true);//隐藏所有行
        }

        if (!item.isEmpty())
        {
            newrows = item.count();
            for (int i = 0; i < item.count(); i++)
            {
                ui->tableWidget_da->setRowHidden(item.at(i)->row(),false);//item.at(i).row()输出行号
            }
        }
    }

    QString newtext = QString(" 共: %1 条").arg(newrows);
    ui->label_2->setText(newtext);
}

//发送信号，调用目录打印操作界面
void DirManage::sendPrintSlot()
{
    emit printSignal();
}

//添加记录行
void DirManage::on_buttonAdd_clicked()
{
    int daCurrentRow = ui->tableWidget_da->currentRow();//获取当前行的Index
    if (daCurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        int d_CurrentRow = ui->listWidget->currentRow();//获取当前行的Index
        if(d_CurrentRow > 0)
        {
            getTableWidget(d_CurrentRow);

            int cols = tableWidget->columnCount();
            int rows = tableWidget->rowCount();
            //qDebug() << rows << cols;

            tableWidget->insertRow(rows);

            for(int i=0;i<cols;i++)
            {
                tableWidget->setItem(rows,i,new QTableWidgetItem(""));
            }

            tableWidget->selectRow(rows);
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("未选择档案类别！"));
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("未选择干部信息记录！"));
    }

}

//删除记录行
void DirManage::on_buttonDel_clicked()
{
    int daCurrentRow = ui->tableWidget_da->currentRow();
    if (daCurrentRow != -1)
    {
        int daClassRow = ui->listWidget->currentRow();
        if (daClassRow > 0)
        {
            getTableWidget(daClassRow);

            int mlCurrentRow = tableWidget->currentRow();
            if (mlCurrentRow != -1)
            {
                QMessageBox::StandardButton result;
                result = QMessageBox::question(this,"确认消息框","确认删除该条记录？",QMessageBox::Yes|QMessageBox::No);
                if(result==QMessageBox::Yes)
                {
                    //删除数据库对应记录
                    QString idNum = ui->tableWidget_da->item(daCurrentRow, 2)->text();
                    QString materialName = tableWidget->item(mlCurrentRow, 0)->text();

                    QSqlQuery query;
                    QString sql = QString("delete from ArchiveDirectoryInfo where IDNum = '%1' and MaterialName = '%2'").arg(idNum).arg(materialName);
                    if(query.exec(sql)) QMessageBox::information(this,"提示信息","删除成功");

                    QTableWidgetItem * item = tableWidget->currentItem();
                    if(item == 0) return;
                    tableWidget->removeRow(item->row());

                }
                else if(result==QMessageBox::No)
                {
                    return;
                }
            }
            else
            {
                QMessageBox::critical(this, tr("错误！"), tr("未选择目录记录！"));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("未选择档案类别！"));
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("未选择干部记录！"));
    }
}

//交换两行记录数据
void DirManage::SwapTwoRow(int selectRow, int targetRow)
{
    int rowNow = ui->listWidget->currentRow();
    getTableWidget(rowNow);

    QStringList selectRowLine, targetRowLine;//创建两个QStringList用于储存表格数据
    int colCount = tableWidget->columnCount();
    for (int i = 0; i < colCount; i++)
    {
        selectRowLine.append(tableWidget->item(selectRow, i)->text());//获取文本，并添加进QStringLine
        targetRowLine.append(tableWidget->item(targetRow, i)->text());
    }
    for (int i = 0; i < colCount; i++)
    {
        tableWidget->setItem(selectRow, i, new QTableWidgetItem(targetRowLine.at(i))); //设置文本
        tableWidget->setItem(targetRow, i, new QTableWidgetItem(selectRowLine.at(i)));
    }
}

//上移
void DirManage::on_buttonUp_clicked()
{
    int d_CurrentRow = ui->listWidget->currentRow();//获取当前行的Index
    if (d_CurrentRow > 0)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        int rowNow = ui->listWidget->currentRow();
        getTableWidget(rowNow);

        int m_CurrentRow = tableWidget->currentRow();//获取当前行的Index
        if (m_CurrentRow != -1)//如果选中了数据，（未选择数据之前，返回值是-1）
        {
            if (m_CurrentRow != 0)//如果选定行不在第一行
            {
                SwapTwoRow(m_CurrentRow, m_CurrentRow - 1);
                tableWidget->setCurrentCell(m_CurrentRow - 1, QItemSelectionModel::Select);//移动过后继续选定该行
            }
        }
        else
        {
           if (tableWidget->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
           {
                QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
           }
           else
           {
                QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
           }
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
    }
}

//下移
void DirManage::on_buttonDown_clicked()
{
    int d_CurrentRow = ui->listWidget->currentRow();//获取当前行的Index
    if (d_CurrentRow > 0)//如果选中了数据，（未选择数据之前，返回值是-1）
    {
        int rowNow = ui->listWidget->currentRow();
        getTableWidget(rowNow);

        int m_CurrentRow = tableWidget->currentRow();
        if (m_CurrentRow != -1)//如果选中了一行
        {
            if (m_CurrentRow != (tableWidget->rowCount() - 1))//如果不是最后一行
            {
                SwapTwoRow(m_CurrentRow, m_CurrentRow + 1);
                tableWidget->setCurrentCell(m_CurrentRow + 1, QItemSelectionModel::Select);//移动过后继续选定该行
            }

        }
        else
        {
            if (tableWidget->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
            {
                QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
            }
            else
            {
                QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
            }
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选择数据！"));
    }
}

//档案目录制作widget切换
void DirManage::on_listWidget_currentRowChanged(int currentRow)
{
    int dacurrentRow = ui->tableWidget_da->currentRow();

    if (dacurrentRow != -1)//如果选中了一行
    {
        if(currentRow == 4 or currentRow == 13)
        {
            ui->buttonAdd->setEnabled(false);
            ui->buttonDel->setEnabled(false);
            ui->buttonUp->setEnabled(false);
            ui->buttonDown->setEnabled(false);
            ui->buttonInsert->setEnabled(false);
        }
        else
        {
            ui->buttonAdd->setEnabled(true);
            ui->buttonDel->setEnabled(true);
            ui->buttonUp->setEnabled(true);
            ui->buttonDown->setEnabled(true);
            ui->buttonInsert->setEnabled(true);
        }

        if(currentRow == 1 or currentRow == 2 or currentRow == 3)
            ui->stackedWidget->setCurrentIndex(currentRow-1);
        if(currentRow == 5 or currentRow == 6 or currentRow == 7 or currentRow == 8 or currentRow == 9 or currentRow == 10 or currentRow == 11 or currentRow == 12)
            ui->stackedWidget->setCurrentIndex(currentRow-2);
        if(currentRow == 14 or currentRow == 15 or currentRow == 16 or currentRow == 17 or currentRow == 18)
            ui->stackedWidget->setCurrentIndex(currentRow-3);

        getTableWidget(currentRow);

        tableWidget->setRowCount(0);

        QString classNum;

        QString sqlClass = QString("select ClassNum from ArchiveClassCode where Description = '%1'").arg(currentRow);

        QSqlQuery queryClass;
        queryClass.exec(sqlClass);
        while(queryClass.next()) //一行一行遍历
        {
            classNum = queryClass.value(0).toString();
            //qDebug()<<classNum;
        }

        QString idNum = ui->tableWidget_da->item(dacurrentRow,2)->text();

        QSqlQuery query;
        QString sql = QString("select MaterialName, Creatime, PageNum, CopyNum, Description from ArchiveDirectoryInfo where IDNum = '%1' and ClassNum = '%2'").arg(idNum).arg(classNum);
        query.exec(sql);
        while(query.next())
        {
            int rows = tableWidget->rowCount();
            tableWidget->insertRow(rows);

            for(int i=0;i<5;i++)
                tableWidget->setItem(rows,i, new QTableWidgetItem(query.value(i).toString()));
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("未选中干部记录！"));
    }

}

//获取当前tableWidget
void DirManage::getTableWidget(int count)
{
    switch (count) {
    case 1:
        tableWidget = ui->tableWidget_ml_1;
        break;
    case 2:
        tableWidget = ui->tableWidget_ml_2;
        break;
    case 3:
        tableWidget = ui->tableWidget_ml_3;
        break;
    case 5:
        tableWidget = ui->tableWidget_ml_4;
        break;
    case 6:
        tableWidget = ui->tableWidget_ml_5;
        break;
    case 7:
        tableWidget = ui->tableWidget_ml_6;
        break;
    case 8:
        tableWidget = ui->tableWidget_ml_7;
        break;
    case 9:
        tableWidget = ui->tableWidget_ml_8;
        break;
    case 10:
        tableWidget = ui->tableWidget_ml_9;
        break;
    case 11:
        tableWidget = ui->tableWidget_ml_10;
        break;
    case 12:
        tableWidget = ui->tableWidget_ml_11;
        break;
    case 14:
        tableWidget = ui->tableWidget_ml_12;
        break;
    case 15:
        tableWidget = ui->tableWidget_ml_13;
        break;
    case 16:
        tableWidget = ui->tableWidget_ml_14;
        break;
    case 17:
        tableWidget = ui->tableWidget_ml_15;
        break;
    case 18:
        tableWidget = ui->tableWidget_ml_16;
        break;
    case 4:break;
    case 13:break;
    default:
        break;
    }
}

//导出xml
void DirManage::on_buttonInOut_clicked()
{
    int currentRow = ui->tableWidget_da->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        QString fileName = QFileDialog::getSaveFileName( this, "Save", "../", "*.xml" );
        if (QFileInfo(fileName).suffix().isEmpty())
        {
            fileName.append(".xml");
        }
        QFile file( fileName );
        if( true == file.exists() ) //如果存在不创建
        {
            cout << "文件已经存在";
            return;
        }
        else
        { //不存在才创建
            //只写方式打开文件
            bool isOk = file.open(QIODevice::WriteOnly);
            if(true == isOk)//如果打开成功
            {
                //创建xml文档对象
                QDomDocument doc;
                //创建xml头部格式 <?xml version='1.0' encoding='utf-8'?>
                QDomProcessingInstruction ins;
                ins = doc.createProcessingInstruction("xml", "version=\'1.0\' encoding=\'utf-8\'");
                //追加元素
                doc.appendChild(ins);

                //根节点元素
                QDomElement root = doc.createElement("档案目录表");
                doc.appendChild(root);
                //创建干部信息子节点元素
                QDomElement gbEmt = doc.createElement("干部信息");

                //把节点追加到根节点上
                root.appendChild(gbEmt);

                //干部信息元素
                QDomElement cadreName = doc.createElement("姓名");
                QDomElement sex= doc.createElement("性别");
                QDomElement birth = doc.createElement("出生时间");
                QDomElement nativePlace = doc.createElement("籍贯");

                int row =  ui->tableWidget_da->currentRow();

                QString nameText = ui->tableWidget_da->item(row,0)->text();
                //qDebug()<<nameText;

                QString sexText = ui->tableWidget_da->item(row,1)->text();
                //qDebug()<<sexText;

                QString birthText = ui->tableWidget_da->item(row,7)->text();
                //qDebug()<<birthText;

                QString jgText = ui->tableWidget_da->item(row,8)->text();
                //qDebug()<<jgText;

                QDomText text = doc.createTextNode(nameText);
                cadreName.appendChild(text);

                text = doc.createTextNode(sexText);
                sex.appendChild(text);

                text = doc.createTextNode(birthText);
                birth.appendChild(text);

                text = doc.createTextNode(jgText);
                nativePlace.appendChild(text);

                gbEmt.appendChild(cadreName);
                gbEmt.appendChild(sex);
                gbEmt.appendChild(birth);
                gbEmt.appendChild(nativePlace);

                //创建档案材料子节点元素
                QDomElement dmEmt = doc.createElement("档案材料");
                //把节点追加到根节点上
                root.appendChild(dmEmt);

                //手动制作档案目录记录
                int rows_da = ui->listWidget->count();

                for (int i = 1; i < rows_da ; i++)
                {

                    QString itemText = ui->listWidget->item(i)->text();
                    //qDebug()<<itemText;

                    //档案目录信息元素
                    QDomElement fileKind = doc.createElement("档案类别");
                    QString fkText = itemText;
                    QDomText text = doc.createTextNode(fkText);
                    fileKind.appendChild(text);
                    dmEmt.appendChild(fileKind);

                    getTableWidget(i);

                    int rows_ml = tableWidget->rowCount();

                    for(int j=0;j<rows_ml;j++)
                    {

                        //创建目录记录子节点元素
                        QDomElement mlEmt = doc.createElement("目录记录");
                        //把节点追加到根节点上
                        dmEmt.appendChild(mlEmt);

                        QDomElement dirName = doc.createElement("档案目录名称");
                        QDomElement makeTime= doc.createElement("制成时间");
                        QDomElement pageNum= doc.createElement("页数");
                        QDomElement paperNum = doc.createElement("份数");
                        QDomElement remark = doc.createElement("备注");


                        QString dnText = tableWidget->item(j,0)->text();
                        text = doc.createTextNode(dnText);
                        dirName.appendChild(text);

                        QString mtText = tableWidget->item(j,1)->text();
                        text = doc.createTextNode(mtText);
                        makeTime.appendChild(text);

                        QString pnText = tableWidget->item(j,2)->text();
                        text = doc.createTextNode(pnText);
                        pageNum.appendChild(text);

                        QString rnText = tableWidget->item(j,3)->text();
                        text = doc.createTextNode(rnText);
                        paperNum.appendChild(text);

                        QString rkText = tableWidget->item(j,4)->text();
                        text = doc.createTextNode(rkText);
                        remark.appendChild(text);

                        mlEmt.appendChild(dirName);
                        mlEmt.appendChild(makeTime);
                        mlEmt.appendChild(pageNum);
                        mlEmt.appendChild(paperNum);
                        mlEmt.appendChild(remark);
                     }
                }

                //保存
                QTextStream stream(&file); //文本流关联文件
                doc.save(stream, 4); //4 缩进字符
                file.close(); //关闭文件

                QMessageBox::information(this,"提示","导出成功！");
            }
            else
            {
                cout << "WriteOnly error";
                return;
            }
        }
    }
    else
    {
        if (ui->tableWidget_da->rowCount() != 0)//如果有数据，但是currentRow=--1 说明没有选择数据,把焦点定位到第一行
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：未选中干部！"));
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("无法移动：表格中没有数据！"));
        }
    }
}

//档案编辑
void DirManage::on_buttonEdit_clicked()
{
    emit fileEdit();
    //frm.show();
}

//刷新当前界面档案信息
void DirManage::on_buttonRefresh_clicked()
{
    ui->tableWidget_da->setRowCount(0);
    showCadreFileData();
}

//形成html
QString DirManage::saveHtmlToPDF(QString fileName)
{
    QString html = "";
    html += "<html>";
    html += "<head>";
    html += "<title>"+fileName+"</title>";
    html += "<head>";
    html += "<body>";
    html += "<h1>干部档案目录信息</h1>";
    //html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<td align=\"center\" height=\"60\">------干部信息------</td>";
        html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    int row =  ui->tableWidget_da->currentRow();
    html += "<tr>";
        html += "<th>干部姓名</th>";
        html += "<th>性别</th>";
        html += "<th>出生时间</th>";
        html += "<th>籍贯</th>";
    html += "</tr>";
    html += "<tr>";
        html += "<th>"+ui->tableWidget_da->item(row,0)->text()+"</th>";
        html += "<th>"+ui->tableWidget_da->item(row,1)->text()+"</th>";
        html += "<th>"+ui->tableWidget_da->item(row,7)->text()+"</th>";
        html += "<th>"+ui->tableWidget_da->item(row,8)->text()+"</th>";
    html += "</tr>";
    html += "</table>";

    html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
    html += "<tr>";
        html += "<td align=\"center\" height=\"60\">------档案材料目录------</td>";
    html += "</tr>";
    html += "</table>";

    int rows_da = ui->listWidget->count();

    for (int i = 1; i < rows_da ; i++)
    {

        QString itemText = ui->listWidget->item(i)->text();

        html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<td align=\"center\" height=\"60\">            </td>";
        html += "</tr>";
        html += "</table>";

        html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<th>档案类别</th>";
            html += "<th>"+ itemText +"</th>";
        html += "</tr>";
        html += "</table>";

        html += "<table width=\"100%\" border=\"1\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
        html += "<tr>";
            html += "<th>档案目录名称</th>";
            html += "<th>制成时间</th>";
            html += "<th>页数</th>";
            html += "<th>份数</th>";
            html += "<th>备注</th>";
        html += "</tr>";

        getTableWidget(i);

        int rows_ml = tableWidget->rowCount();

        for(int j=0;j<rows_ml;j++)
        {
            html += "<tr>";
                html += "<th>"+tableWidget->item(j,0)->text()+"</th>";
                html += "<th>"+tableWidget->item(j,1)->text()+"</th>";
                html += "<th>"+tableWidget->item(j,2)->text()+"</th>";
                html += "<th>"+tableWidget->item(j,3)->text()+"</th>";
                html += "<th>"+tableWidget->item(j,4)->text()+"</th>";
            html += "</tr>";
        }

        html += "</table>";
    }
    html += "</body>";
    html += "</html>";
    return html;

}

//打印-形成pdf并打开
void DirManage::on_buttonPrint_clicked()
{
    int currentRow = ui->tableWidget_da->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        QString fileName = QFileDialog::getSaveFileName( this, "导出PDF文件", "../", "*.pdf" );

        if (!fileName.isEmpty())
        {
            // 如果文件后缀为空，则默认使用.pdf
            if (QFileInfo(fileName).suffix().isEmpty())
            {
                fileName.append(".pdf");
            }

            QPrinter *printer = new QPrinter(QPrinter::ScreenResolution);
            // 指定输出格式为pdf
            printer->setPageSize(QPrinter::A4);
            printer->setOutputFormat(QPrinter::PdfFormat);
            printer->setOutputFileName(fileName);

            QTextDocument document;
            document.setHtml(saveHtmlToPDF(fileName));
            document.print(printer);
            document.end();

            QString strPdf = fileName;
            //qDebug()<<strPdf;
            QDesktopServices::openUrl(QUrl::fromLocalFile(strPdf));
        }
     }
    else
    {
        QMessageBox::information(this,"提示信息","未选择打印条目行!");
    }
}

//选择干部默认显示其第一类档案材料目录记录
void DirManage::on_tableWidget_da_itemSelectionChanged()
{
    int currentRow = ui->tableWidget_da->currentRow();
    if (currentRow != -1)//如果选中了一行
    {
        //首先默认显示第一类
        int widgetNum = 1;
        ui->listWidget->setCurrentRow(widgetNum);
        ui->stackedWidget->setCurrentIndex(widgetNum-1);
        getTableWidget(widgetNum);
        tableWidget->setRowCount(0);

        QString idNum = ui->tableWidget_da->item(currentRow,2)->text();
        QSqlQuery query;
        QString sql = QString("select MaterialName, Creatime, PageNum, CopyNum, Description from ArchiveDirectoryInfo where IDNum = '%1' and ClassNum = '%2'").arg(idNum).arg(widgetNum);
        query.exec(sql);
        while(query.next())
        {
            int rows = tableWidget->rowCount();
            tableWidget->insertRow(rows);

            for(int i=0;i<5;i++)
                tableWidget->setItem(rows,i, new QTableWidgetItem(query.value(i).toString()));
        }
    }
}

//插入记录至数据库表
void DirManage::on_buttonInsert_clicked()
{
    int mlClassRow = ui->listWidget->currentRow();
    if(mlClassRow != 4 or mlClassRow != 13)
    {
        int daCurrentRow = ui->tableWidget_da->currentRow();
        if (daCurrentRow != -1)//当前选择行,数据插入表
        {
            QMessageBox::StandardButton result;
            result = QMessageBox::question(this,"确认消息框","确定信息正确并插入记录？",QMessageBox::Yes|QMessageBox::No);
            if(result==QMessageBox::Yes)
            {
                QString classNum = "null";
                QString materialName = "null";
                QString orderNum = "null";
                QString creatime = "null";
                int pageNum = 0;
                int copyNum = 0;
                QString description = "";

                //int mlClassRow = ui->listWidget->currentRow();
                getTableWidget(mlClassRow);

                int mlCurrentRow = tableWidget->currentRow();
                if (mlCurrentRow != -1)//当前选择行,数据插入表
                {
                    //证件号码
                    QString idNum = ui->tableWidget_da->item(daCurrentRow,2)->text();
                    //材料类别

                    QString sqlClass = QString("select ClassNum from ArchiveClassCode where Description = '%1'").arg(mlClassRow);
                    QSqlQuery queryClass;
                    queryClass.exec(sqlClass);
                    while(queryClass.next()) //一行一行遍历
                    {
                        classNum = queryClass.value(0).toString();
                    }

                    //序号
                    if(mlClassRow == 5 or mlClassRow == 14)  orderNum = "1";
                    if(mlClassRow == 6 or mlClassRow == 15)  orderNum = "2";
                    if(mlClassRow == 7 or mlClassRow == 16)  orderNum = "3";
                    if(mlClassRow == 8 or mlClassRow == 17)  orderNum = "4";

                    //材料名称
                    if(tableWidget->item(mlCurrentRow,0)->text() != "")
                        materialName = tableWidget->item(mlCurrentRow,0)->text();
                    //创建时间
                    if(tableWidget->item(mlCurrentRow,1)->text() != "")
                        creatime = tableWidget->item(mlCurrentRow,1)->text();
                    //页数
                    if(tableWidget->item(mlCurrentRow,2)->text() != "")
                        pageNum = tableWidget->item(mlCurrentRow,2)->text().toInt();
                    //份数
                    if(tableWidget->item(mlCurrentRow,3)->text() != "")
                        copyNum = tableWidget->item(mlCurrentRow,3)->text().toInt();
                    //描述
                    if(tableWidget->item(mlCurrentRow,4)->text() != "")
                        description = tableWidget->item(mlCurrentRow,4)->text();

                    QString sql;
                    if(orderNum!="null")
                        sql = QString ("insert into ArchiveDirectoryInfo(IDNum, ClassNum, OrderNum, MaterialName, Creatime, PageNum, CopyNum, Description) values('%1','%2','%3','%4','%5','%6','%7','%8')").arg(idNum).arg(classNum).arg(orderNum).arg(materialName).arg(creatime).arg(pageNum).arg(copyNum).arg(description);
                    else
                        sql = QString ("insert into ArchiveDirectoryInfo(IDNum, ClassNum, OrderNum, MaterialName, Creatime, PageNum, CopyNum, Description) values('%1','%2',null,'%3','%4','%5','%6','%7')").arg(idNum).arg(classNum).arg(materialName).arg(creatime).arg(pageNum).arg(copyNum).arg(description);
                    //qDebug()<<sql;
                    QSqlQuery query;
                    if(query.exec(sql))
                    {
                        QMessageBox::information(this,"提示信息","插入成功");
                    }
                    else
                    {
                        //qDebug()<<idNum<<classNum<<orderNum<<materialName<<creatime<<pageNum<<copyNum<<description;

                        if(materialName == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入正确的目录名称！"), QMessageBox::tr("确定"));
                        }
                        if(creatime == "null"){
                            QMessageBox::information(this, tr("提示"), tr("请输入的时间(yyyy-mm-dd)"), QMessageBox::tr("确定"));
                        }
                        if(pageNum == 0){
                            QMessageBox::information(this, tr("提示"), tr("请输入页数！"), QMessageBox::tr("确定"));
                        }
                        if(copyNum == 0){
                            QMessageBox::information(this, tr("提示"), tr("请输入份数！"), QMessageBox::tr("确定"));
                        }
                        //QMessageBox::information(this,"提示信息","信息不完善或不正确，请重试");
                    }
                }
                else
                {
                    if (tableWidget->rowCount() != 0)
                    {
                        QMessageBox::critical(this, tr("错误！"), tr("未选中待插入记录！"));
                    }
                    else
                    {
                        QMessageBox::critical(this, tr("错误！"), tr("表格中没有数据！"));
                    }
                }
            }
            else if(result==QMessageBox::No)
            {
                return;
            }
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("未选中干部记录！"));
        }

    }
}



/*
void DirManage::PrepareForEdit(int widCount)
{
    getTableWidget(widCount);
    QString idNumPre;
    QString classNumPre;
    QString orderNumPre;
    QString materialNamePre;
    QString creatTimePre;
    int pageNumPre = 0;
    int copyNumPre = 0;
    QString descriptionPre;

    int daRow =  ui->tableWidget_da->currentRow();
    idNumPre = ui->tableWidget_da->item(daRow,2)->text();

    QString mlClassText = ui->listWidget->currentItem()->text();
    QString sqlClass = QString("select ClassNum from ArchiveClassCode where Description = '%1'").arg(mlClassText);
    QSqlQuery queryClass;
    queryClass.exec(sqlClass);
    while(queryClass.next()) //一行一行遍历
    {
        classNumPre = queryClass.value(0).toString();
    }
    //序号
    if(mlClassText == "四1学历学位材料" or mlClassText == "九1工资材料")  orderNumPre = "1";
    if(mlClassText == "四2任职职务资格材料" or mlClassText == "九2任免材料")  orderNumPre = "2";
    if(mlClassText == "四3科研学术材料" or mlClassText == "九3出国材料")  orderNumPre = "3";
    if(mlClassText == "四4培训材料" or mlClassText == "九4党人代会")  orderNumPre = "4";

    int mlRow = tableWidget->currentRow();
    materialNamePre = tableWidget->item(mlRow,0)->text();
    creatTimePre = tableWidget->item(mlRow,1)->text();
    pageNumPre = tableWidget->item(mlRow,2)->text().toInt();
    copyNumPre = tableWidget->item(mlRow,3)->text().toInt();
    descriptionPre = tableWidget->item(mlRow,4)->text();
    qDebug()<<idNumPre<<classNumPre<<orderNumPre<<materialNamePre<<creatTimePre<<pageNumPre<<copyNumPre<<descriptionPre;
    dirIDPre=pageNumPre;
    QSqlQuery query;
    QString sql = QString("select DirectoryId from ArchiveDirectoryInfo where IDNum ='%1' and ClassNum ='%2' and OrderNum = '%3' and MaterialName ='%4' and Creatime ='%5' and PageNum ='%6' and CopyNum ='%7' and Description = '%8'").arg(idNumPre)
            .arg(classNumPre).arg(orderNumPre).arg(materialNamePre).arg(creatTimePre).arg(pageNumPre).arg(copyNumPre).arg(descriptionPre);
    query.exec(sql);
    qDebug()<<sql;
    while(query.next()) //一行一行遍历
    {
        qDebug()<<query.value(0).toInt();
    }
    //qDebug()<<dirIDPre;
    //emit sendData(idNumPre,classNumPre,materialNamePre,creatTimePre,pageNumPre,copyNumPre,descriptionPre);
}

void DirManage::on_buttonModify_clicked()
{

    int daCurrentRow = ui->tableWidget_da->currentRow();
    if (daCurrentRow != -1)
    {
        int d_CurrentRow = ui->listWidget->currentRow();
        if (d_CurrentRow > 0)
        {
            getTableWidget(d_CurrentRow);
            int mlCurrentRow = tableWidget->currentRow();
            if (mlCurrentRow != -1)
            {
                QString mnNow = tableWidget->item(mlCurrentRow,0)->text();
                QString ctNow = tableWidget->item(mlCurrentRow,1)->text();
                int pnNow = tableWidget->item(mlCurrentRow,2)->text().toInt();
                int cnNow  = tableWidget->item(mlCurrentRow,3)->text().toInt();
                QString dNow = tableWidget->item(mlCurrentRow,4)->text();
                qDebug()<<mnNow<<ctNow<<pnNow<<cnNow<<dNow;
                QString sql;
                //UPDATE `ZZB`.`ArchiveDirectoryInfo` SET `DirectoryId`='5', `IDNum`='002', `ClassNum`='2', `MaterialName`='mc7', `Creatime`='2020-05-16', `PageNum`='2', `CopyNum`='2' WHERE `DirectoryId`='12';
                sql = QString ("update ArchiveDirectoryInfo set MaterialName ='%1', Creatime ='%2', PageNum ='%3', CopyNum ='%4', Description = '%5' "
                               "WHERE IDNum ='%6', ClassNum ='%7', OrderNum = '%8' MaterialName ='%9', Creatime ='%10', PageNum ='%11', CopyNum ='%12', Description = '%13')")
                        .arg(mnNow).arg(ctNow).arg(pnNow).arg(cnNow).arg(dNow)
                        .arg(idNumPre).arg(classNumPre).arg(orderNumPre).arg(materialNamePre).arg(creatTimePre).arg(pageNumPre).arg(copyNumPre).arg(descriptionPre);
                qDebug()<<sql;
                QSqlQuery query;
                if(query.exec(sql))
                {
                    QMessageBox::information(this,"提示信息","修改成功");
                }
            }
            else
            {
                QMessageBox::critical(this, tr("错误！"), tr("未选择目录记录！"));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("错误！"), tr("未选择档案类别！"));
        }
    }
    else
    {
        QMessageBox::critical(this, tr("错误！"), tr("未选择干部记录！"));
    }
}
*/
